/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.hr.staff;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.hr.staff.StaffFilesDTO;
import com.plian.system.dto.hr.staffBackup.StaffFilesOldDTO;
import com.plian.system.entity.hr.staff.Director;
import com.plian.system.entity.hr.staff.StaffFiles;
import com.plian.system.entity.hr.staff.Supervisor;
import com.plian.system.mapper.hr.hrbackup.StaffFilesOldMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.hr.hrOld.IStaffFilesOldService;
import com.plian.system.service.hr.staff.IDirectorService;
import com.plian.system.service.hr.staff.IStaffFilesService;
import com.plian.system.service.hr.staff.ISupervisorService;
import com.plian.system.vo.hr.staff.StaffFilesVO;
import com.plian.system.vo.hr.staffAnnualBackup.StaffFilesOldVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.hr.hrbackup.StaffFilesOldWrapper;
import com.plian.system.wrapper.hr.staff.StaffFilesWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.BaseConstant.BASE64_KEY;

/**
 * 员工档案
 *
 * @author gangan
 * @since 2019-09-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/stafffiles")
public class StaffFilesController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(StaffFilesController.class);

    private IStaffFilesService staffFilesService;
    private IStaffFilesOldService iStaffFilesOldService;

    private IDirectorService directorService;

    private ISupervisorService supervisorService;


    private StaffFilesWrapper staffFilesWrapper;
    private StaffFilesOldMapper staffFilesOldMapper;
    private StaffFilesOldWrapper staffFilesOldWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<StaffFilesVO> detail(@Valid @RequestBody StaffFilesDTO staffFiles) {
        R<StaffFilesVO> r=new R<>();
        if(staffFiles!=null&&StringUtil.isNotBlank(staffFiles.getYear())){
            String year=staffFiles.getYear();
            LocalDate currentDate = LocalDate.now(); // 获取当前日期
            int currentYear = currentDate.getYear(); // 获取当前年份
            String currentYearStr=String.valueOf(currentYear);
            if(currentYearStr.equals(year)){
                StaffFilesVO staffFilesVO = staffFilesWrapper.entityToVO(staffFilesService.getOne(Condition.getQueryWrapper(staffFiles)));
                r=staffFilesService.getDetailObj(staffFilesVO);
            }else{
                StaffFilesOldDTO  staffFilesOldDTO=new StaffFilesOldDTO();
                BeanUtils.copyProperties(staffFiles,staffFilesOldDTO);
                StaffFilesOldVO staffFilesOldVO = staffFilesOldWrapper.entityToVO(iStaffFilesOldService.getOne(Condition.getQueryWrapper(staffFilesOldDTO)));
                R<StaffFilesOldVO> rOld=iStaffFilesOldService.getDetailObj(staffFilesOldVO);
                BeanUtils.copyProperties(rOld,r);
            }
        }else{
            StaffFilesVO staffFilesVO = staffFilesWrapper.entityToVO(staffFilesService.getOne(Condition.getQueryWrapper(staffFiles)));
            r=staffFilesService.getDetailObj(staffFilesVO);
        }

        return r;
    }

    /**
     * 详情接口（数据脱敏）
     * @param staffFiles
     * @return
     */
    @PostMapping("/dataMaskingDetail")
    public R<StaffFilesVO> dataMaskingDetail(@Valid @RequestBody StaffFilesDTO staffFiles) {
        R<StaffFilesVO> r = this.detail(staffFiles);
        // 脱敏处理
        if (r != null && r.getPageData() != null) {
            StaffFilesVO vo = r.getPageData();
            vo.setDocumentNumber(DesensitizedUtil.desensitized(vo.getDocumentNumber(), DesensitizedUtil.DesensitizedType.ID_CARD));
            vo.setPlaceOfDomicile(DesensitizedUtil.desensitized(vo.getPlaceOfDomicile(), DesensitizedUtil.DesensitizedType.ADDRESS));
            vo.setTelephone(DesensitizedUtil.desensitized(vo.getTelephone(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
            vo.setEmail(DesensitizedUtil.desensitized(vo.getEmail(), DesensitizedUtil.DesensitizedType.EMAIL));
            vo.setWorkPhone(DesensitizedUtil.desensitized(vo.getWorkPhone(), DesensitizedUtil.DesensitizedType.FIXED_PHONE));
            vo.setFamilyAddress(DesensitizedUtil.desensitized(vo.getFamilyAddress(), DesensitizedUtil.DesensitizedType.ADDRESS));
            vo.setEmergencyContactUs(DesensitizedUtil.desensitized(vo.getEmergencyContactUs(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
            r.setPageData(vo);
        }
        return r;
    }

    /**
     * 分页 员工档案
     */
    @PostMapping("/list")
    public ListResult<StaffFilesVO> list(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setAscs("order_number,department_code");
            query.setDescs("create_time,id");
        }

        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<StaffFiles> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new StaffFiles()), entityList
        );
//        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        TokenSearch<StaffFiles> tokenSearch = new TokenSearch<>();
        if(null == query.getFlag()) query.setFlag(1);
        tokenSearch.addTokenQuery(queryWrapper, query);

        queryWrapper.eq("is_out", 1);
        if (StringUtil.isNotBlank(query.getKeyword())) {
            queryWrapper.like("staff_name", query.getKeyword());
        }

        IPage<StaffFiles> pages = staffFilesService.page(Condition.getPage(query), queryWrapper);
        List<StaffFilesVO> staffFilesVOS = staffFilesService.setVO(pages.getRecords());
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 分页 员工档案
     */
    @PostMapping("/qiyeList")
    public ListResult<StaffFilesVO> qiyeList(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setAscs("order_number,department_code");
            query.setDescs("create_time,id");
        }
        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<StaffFiles> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new StaffFiles()), entityList
        );
//        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        queryWrapper.eq("is_out", 1);
        if (StringUtil.isNotBlank(query.getKeyword())) {
            queryWrapper.like("staff_name", query.getKeyword());
        }

        IPage<StaffFiles> pages = staffFilesService.page(Condition.getPage(query), queryWrapper);
        List<StaffFilesVO> staffFilesVOS = staffFilesService.setVO(pages.getRecords());
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 新增或修改 员工档案
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("员工档案-提交")
    public R submit(@Valid @RequestBody StaffFilesVO staffFilesVO) {
        return staffFilesService.submit(staffFilesVO);
    }

    /**
     * 删除 员工档案
     */
    @PostMapping("/remove")
    @LogOperation("员工档案-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return staffFilesService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 禁用 员工档案
     */
    @PostMapping("/disable")
    @LogOperation("员工档案-禁用")
    public R disable(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return staffFilesService.disable(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 启用 员工档案
     */
    @PostMapping("/enable")
    @LogOperation("员工档案-启用")
    public R enable(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return staffFilesService.enable(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }



    /**
     * @param staffFilesDTO
     * @return
     */
    @PostMapping("/report")
    public R<ReportReturnVO> reportTable(@RequestBody StaffFilesDTO staffFilesDTO) {
        ReportReturnVO reportReturnVO=new ReportReturnVO();
        if(staffFilesDTO!=null&&StringUtil.isNotBlank(staffFilesDTO.getYear())){
            String year=staffFilesDTO.getYear();
            LocalDate currentDate = LocalDate.now(); // 获取当前日期
            int currentYear = currentDate.getYear(); // 获取当前年份
            String currentYearStr=String.valueOf(currentYear);
            if(currentYearStr.equals(year)){
                reportReturnVO = staffFilesService.report(staffFilesDTO);
            }else{
                reportReturnVO = iStaffFilesOldService.reportToYear(staffFilesDTO);
            }

        }else{
            reportReturnVO = staffFilesService.report(staffFilesDTO);
        }
        R<ReportReturnVO> objResult = new R<>(CommonCode.SUCCESS);
        objResult.setPageData(reportReturnVO);
        return objResult;

    }

    @PostMapping("/reportChartsGender")
    public R<ReportReturnVO> reportChartsGender(@RequestParam(required = false) Long companyNameId) {
        return staffFilesService.getReportObj(staffFilesService.reportChartsGender(companyNameId));
    }

    @PostMapping("/reportChartsPoliticCountenance")
    public R<ReportReturnVO> reportChartsPoliticCountenance(@RequestParam(required = false) Long companyNameId) {
        return staffFilesService.getReportObj(staffFilesService.reportChartsPoliticCountenance(companyNameId));
    }

    @PostMapping("/reportChartsEducational")
    public R<ReportReturnVO> reportChartsEducational(@RequestParam(required = false) Long companyNameId) {
        return staffFilesService.getReportObj(staffFilesService.reportChartsEducational(companyNameId));
    }

    @PostMapping("/reportChartsWorkTime")
    public R<ReportReturnVO> reportChartsWorkTime(@RequestParam(required = false) Long companyNameId) {
        return staffFilesService.getReportObj(staffFilesService.reportChartsWorkTime(companyNameId));
    }

    /**
     * 打印
     */
    @GetMapping("/buildpdf/{id}")
//    @PassToken
    public ResponseEntity<FileSystemResource> buildPdf(@PathVariable Long id, HttpServletRequest httpServletRequest) {
        String year=httpServletRequest.getParameter("year");
        File file=null;
        if(StringUtil.isNotBlank(year)){
            LocalDate currentDate = LocalDate.now(); // 获取当前日期
            int currentYear = currentDate.getYear(); // 获取当前年份
            String currentYearStr=String.valueOf(currentYear);
            if(year.equals(currentYearStr)){
                file=staffFilesService.createReceptFile(id);
            }else{
                file=iStaffFilesOldService.createReceptFile(id,year);
            }
        }else{
            file=staffFilesService.createReceptFile(id);
        }
        //return FileTools.exportPdf(staffFilesService.buildpdf(id));
        return FileTools.exportPdf(file);
    }

    /**
     * 新增导入(导入时仅导入系统内编码不存在的数据)
     */
    @PostMapping("/excelImport")
    @LogOperation("员工档案-导入")
    public ObjResult excelImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_" + System.currentTimeMillis();
        CacheUtil.put("progress", "progress", progressId + "#half:hour", 0);
        InputStream inputStream = multipartFile.getInputStream();
        staffFilesService.importExcel(progressId, inputStream, false);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 覆盖导入(导入时仅导入系统内编码存在的数据)
     */
    @PostMapping("/excelCoverImport")
    @LogOperation("员工档案-导入")
    public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_" + System.currentTimeMillis();
        CacheUtil.put("progress", "progress", progressId + "#half:hour", 0);
        InputStream inputStream = multipartFile.getInputStream();
        staffFilesService.importExcel(progressId, inputStream, true);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 导入进度查看
     */
    @GetMapping("/progress/{progressId}")
    public ObjResult progress(@PathVariable String progressId) {
        Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
        if (data != null && data instanceof String) {
            if ("导入成功".equals(data)) {
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                PageData pd = new PageData();
                pd.put("data", 200);
                objResult.setPageData(pd);
                return objResult;
            }
            return new ObjResult(CustomCode.builder().message((String) data).code(1000).success(false).build());
        }
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("data", data);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 根据id获取单一对象
     */
    @GetMapping("/getById")
    public R<StaffFilesVO> detail(@RequestParam Long id) {
        return R.data(staffFilesWrapper.entityToVO(staffFilesService.getById(id)));
    }


    /**
     * 分页 用于董事会添加按钮获取上游单据
     */
    @PostMapping("/getDirectorPreList")
    public ListResult<StaffFilesVO> getDirectorPreList(@Valid @RequestBody Query query) {
        QueryWrapper<StaffFiles> queryWrapper = new QueryWrapper<>();
        /**
         * 排除已经被使用的数据
         */
        LambdaQueryWrapper<Director> directorQueryWrapper = new LambdaQueryWrapper<>();
        directorQueryWrapper.eq(Director::getCompanyId, TokenUtil.getTokenOrgId());
        List<Director> directors = directorService.list(directorQueryWrapper);
        List<Long> ids = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(directors)) {
            ids.addAll(directors.stream().filter(director -> director.getStaffFilesId() != null && director.getIsOutDirector() == 1)
                    .map(Director::getStaffFilesId).collect(Collectors.toList()));

        }

        LambdaQueryWrapper<Supervisor> supervisorQueryWrapper = new LambdaQueryWrapper<>();
        supervisorQueryWrapper.eq(Supervisor::getCompanyId, TokenUtil.getTokenOrgId());
        List<Supervisor> supervisors = supervisorService.list(supervisorQueryWrapper);
        if (CollectionUtil.isNotEmpty(supervisors)) {
            ids.addAll(supervisors.stream().filter(supervisor -> supervisor.getStaffFilesId() != null && supervisor.getIsOutSupervisor() == 2)
                    .map(Supervisor::getStaffFilesId).collect(Collectors.toList()));
        }

        if (CollectionUtil.isNotEmpty(ids)) {
            queryWrapper.notIn("id", ids);
        }

        return staffFilesService.getPreList(query, queryWrapper);
    }

    /**
     * 分页 用于监事添加按钮获取上游单据
     */
    @PostMapping("/getSupervisorPreList")
    public ListResult<StaffFilesVO> getSupervisorPreList(@Valid @RequestBody Query query) {
        QueryWrapper<StaffFiles> queryWrapper = new QueryWrapper<>();

        /**
         * 排除已经被使用的数据
         */
        LambdaQueryWrapper<Director> directorQueryWrapper = new LambdaQueryWrapper<>();
        directorQueryWrapper.eq(Director::getCompanyId, TokenUtil.getTokenOrgId());
        List<Director> directors = directorService.list(directorQueryWrapper);
        List<Long> ids = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(directors)) {
            ids.addAll(directors.stream().filter(director -> director.getStaffFilesId() != null && director.getIsOutDirector() == 1)
                    .map(Director::getStaffFilesId).collect(Collectors.toList()));

        }

        LambdaQueryWrapper<Supervisor> supervisorQueryWrapper = new LambdaQueryWrapper<>();
        supervisorQueryWrapper.eq(Supervisor::getCompanyId, TokenUtil.getTokenOrgId());
        List<Supervisor> supervisors = supervisorService.list(supervisorQueryWrapper);
        if (CollectionUtil.isNotEmpty(supervisors)) {
            ids.addAll(supervisors.stream().filter(supervisor -> supervisor.getStaffFilesId() != null && supervisor.getIsOutSupervisor() == 2)
                    .map(Supervisor::getStaffFilesId).collect(Collectors.toList()));
        }

        if (CollectionUtil.isNotEmpty(ids)) {
            queryWrapper.notIn("id", ids);
        }

        return staffFilesService.getPreList(query, queryWrapper);

    }

    /**
     * 分页员工档案
     */
    @PostMapping("/getByCompanyId")
    public ListResult<StaffFilesVO> getByCompanyId(@Valid @RequestBody StaffFiles staffFiles) {
        LambdaQueryWrapper<StaffFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StaffFiles::getCompanyNameId, staffFiles.getCompanyNameId());
        queryWrapper.eq(StaffFiles::getDef18, 1);
        queryWrapper.eq(StaffFiles::getIsOut, 1);

        List<StaffFilesVO> staffFilesVOS = staffFilesService.setVO(staffFilesService.list(queryWrapper));
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(staffFilesVOS.size());
        return listResult;
    }

    /**
     * 查询员工的人事档案信息和补充信息
     *
     * @param staffFiles
     * @return
     */
    @PostMapping("/getBaseInfoByCompanyId")
    public ListResult<StaffFilesVO> getBaseInfoByCompanyId(@Valid @RequestBody StaffFiles staffFiles) {
        LambdaQueryWrapper<StaffFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StaffFiles::getCompanyNameId, staffFiles.getCompanyNameId());
        queryWrapper.eq(StaffFiles::getDef18, 1);
        queryWrapper.eq(StaffFiles::getIsOut, 1);

        List<StaffFilesVO> staffFilesVOS = staffFilesService.getBaseInfoByCompanyId(staffFilesService.list(queryWrapper));
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(staffFilesVOS.size());
        return listResult;
    }


    @GetMapping("/exportTemplateExcel")
//    @PassToken
    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
        staffFilesService.exportTemplateExcel(response, os);
    }

    /**
     * 分页 获取所有已审批的员工档案列表，和登录用户无关
     */
    @PostMapping("/allList")
    public ListResult<StaffFilesVO> allList(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }

        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<StaffFiles> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new StaffFiles()), entityList
        );
        queryWrapper.eq("def18", 1);
        queryWrapper.eq("is_out", 1);
        IPage<StaffFiles> pages = staffFilesService.page(Condition.getPage(query), queryWrapper);
        List<StaffFilesVO> staffFilesVOS = staffFilesService.setVO(pages.getRecords());
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 根据部门获取人员
     */
    @PostMapping("/getByDept")
    public ListResult<StaffFilesVO> getByDept(@RequestBody StaffFilesVO staffFilesVO) {
        List<StaffFilesVO> staffFilesVOS = staffFilesWrapper.entityToVO(staffFilesService.getByDept(staffFilesVO.getDepartmentNameId()));
        if (CollectionUtil.isNotEmpty(staffFilesVOS)) {
            for (StaffFilesVO vo : staffFilesVOS) {
                if ("企业负责人".equals(staffFilesVO.getDepartmentNameId())) {
                    vo.setDepartmentName("企业负责人");
                    vo.setDepartmentNameId(null);
                    vo.setIsLeader(2);
                } else {
                    vo.setIsLeader(1);
                }

                if (StringUtil.isNotBlank(vo.getManagementCategoryId()) && "027002".equals(vo.getManagementCategoryId())) {
                    vo.setIsMiddle(2);
                    vo.setMiddleAverageNumber(new BigDecimal(1));
                } else {
                    vo.setIsMiddle(1);
                }
                vo.setAverageNumber(new BigDecimal(1));
            }
        }
        ListResult<StaffFilesVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(staffFilesVOS);
        return listResult;

    }


    /**
     * 生成可以导入的excel文件
     *
     * @return
     */
    @GetMapping("/exportImportFile")
    public ObjResult exportImportFile() {
        PageData pd = new PageData();
        pd.put("key", staffFilesService.exportImportFile());
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 下载excel文件 并删除
     *
     * @param key
     * @param response
     */
    @GetMapping("/download/{key}")
//    @PassToken
    public void download(@PathVariable String key, HttpServletResponse response) {
        staffFilesService.download(key, response);
    }

    @GetMapping("/encryptBase64Data")
    public void encryptBase64Data() {
        List<StaffFiles> staffFilesList = staffFilesService.list(Wrappers.<StaffFiles>lambdaQuery().isNotNull(StaffFiles::getStaffCode));
        for (StaffFiles staffFiles : staffFilesList) {
            if (StringUtil.isNotBlank(staffFiles.getStaffCode())) {
                staffFiles.setStaffCode(EncryptUtil.encryptBase64(staffFiles.getStaffCode(), BASE64_KEY));
            }
            if (StringUtil.isNotBlank(staffFiles.getDocumentNumber())) {
                staffFiles.setDocumentNumber(EncryptUtil.encryptBase64(staffFiles.getDocumentNumber(), BASE64_KEY));
            }
        }
        staffFilesService.updateBatchById(staffFilesList);
    }

}
